package archer.back.models

import java.sql.Timestamp
import java.util.Date

import com.alibaba.vo.HMACSha1Encode
import io.circe.Json
import io.circe.generic.JsonCodec
import io.circe.syntax._

@JsonCodec
case class CacheWrap(planId: Int, actionId: Int, cacheUrl: String) {

  /**
   * 为 url 做了散列处理的原 case class 转化为 json 的 string，防止 es 的 id 字段超长
   */
  lazy val elasticKey: String =
    this.copy(cacheUrl = this.urlShaKey).asJson.noSpaces

  lazy val urlShaKey: String = HMACSha1Encode.HMACSha1(cacheUrl)

}

case class IndexTaskWrap(
  cache: CacheWrap,
  body: CommonBody,
  afterIndexed: () => Unit) {

  import models.CrawlTables._

  lazy val subsModel: List[CrawlUrlsRow] =
    body.subs.map { sub =>
      val cacheWrap = CacheWrap(
        planId = cache.planId,
        actionId = cache.actionId,
        cacheUrl = sub.url)
      CrawlUrlsRow(
        id = cacheWrap.urlShaKey,
        refer = body.url,
        url = sub.url,
        deep = body.deep + 1,
        finishedCrawl = false,
        requestTime = new Timestamp(new Date().getTime),
        planId = cache.planId,
        actionId = cache.actionId)
    }

}
